package com.hs.srm.admin.modules.harmfulsubstance.controller;

import cn.hutool.core.util.ObjectUtil;
import com.hs.srm.admin.modules.harmfulsubstance.entity.DeclarationFormHeadEntity;
import com.hs.srm.admin.modules.harmfulsubstance.entity.DeclarationFormItemEntity;
import com.hs.srm.admin.modules.harmfulsubstance.service.DeclarationFormHeadService;
import com.hs.srm.admin.modules.harmfulsubstance.service.DeclarationFormItemService;
import com.hs.srm.admin.modules.harmfulsubstance.service.ReportRepositoryService;
import com.hs.srm.admin.modules.harmfulsubstance.vo.DeclarationFormVO;
import com.hs.srm.admin.modules.sys.controller.AbstractController;
import com.hs.srm.admin.modules.vendor.entity.VendorInfoEntity;
import com.hs.srm.admin.modules.vendor.service.VendorService;
import com.hs.srm.base.modules.sys.entity.SysUserEntity;
import com.hs.srm.common.utils.PageUtils;
import com.hs.srm.common.utils.R;
import com.hs.srm.tools.FileUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 宣告表
 *
 * @author ych
 * @since 2020-03-24 13:29:50
 */
@RestController
@RequestMapping("/declarationForm")
public class DeclarationFormController extends AbstractController {

    @Value("${hssrm.file-upload-path}")
    protected String fileUploadPath;

    @Autowired
    private DeclarationFormHeadService declarationFormHeadService;

    @Autowired
    private VendorService vendorService;

    @Autowired
    private DeclarationFormItemService declarationFormItemService;

    @Autowired
    private ReportRepositoryService reportService;

    /**
     * 查询列表
     *
     * @param params
     * @return
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        SysUserEntity username = this.getUser();
        if (username.getDeptId() == 13) {
            params.put("username", username.getUsername());
        }
        PageUtils page = declarationFormHeadService.queryPage(params);
        return R.ok(page);
    }


    /**
     * 宣告表新增页面
     *
     * @return
     */
    @RequiresPermissions("declarationForm:add")
    @GetMapping("/addDeclarationForm")
    public ModelAndView addDeclarationForm() {
        ModelAndView modelAndView = new ModelAndView("modules/harmful/rohs/declaration_add");
        VendorInfoEntity vendor = vendorService.selectByVendorCode(this.getUser().getUsername());
        if (ObjectUtil.isNotNull(vendor)) {
            modelAndView.addObject("vendorCode", vendor.getSapCode());
            modelAndView.addObject("vendorName", vendor.getVendorName());
        }
        return modelAndView;
    }

    /**
     * 宣告表详情页面
     *
     * @return
     */
    @GetMapping("/declarationDetails/{pkId}")
    public ModelAndView declarationDetails(@PathVariable("pkId") String headId) {
        ModelAndView modelAndView = new ModelAndView("modules/harmful/rohs/declaration_details");
        DeclarationFormHeadEntity headEntity = declarationFormHeadService.selectById(headId);
        List<DeclarationFormVO> list = declarationFormItemService.selectDetails(headId);
        for (DeclarationFormVO entity : list) {
            //将附件前的路径去掉及上传文件时添加的时间，返回文件名。例：/aaa/bb/asd_20201010121212.txt --> asd.txt
            entity.setThirdAttachment(entity.getThirdAttachment().substring(entity.getThirdAttachment().lastIndexOf("/") + 1));
            entity.setThirdAttachment(entity.getThirdAttachment().replaceAll("_\\d+", ""));
        }
        modelAndView.addObject("declarationDetails", list);
        modelAndView.addObject("head", headEntity);
        return modelAndView;
    }

    /**
     * 根据id下载附件
     */
    @RequestMapping("/downloadFileById")
    public void downloadFileById(String id, HttpServletRequest request, HttpServletResponse response) throws IOException {
        DeclarationFormItemEntity ec = declarationFormItemService.selectById(id);
        File file = new File(this.fileUploadPath + ec.getThirdAttachment());
        FileUtils.fileDownload(file, request, response);
    }

    /**
     * 宣告表新增
     *
     * @param declarationVO
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @RequiresPermissions("declarationForm:add")
    @PostMapping("/declarationAdd")
    public R declarationAdd(@RequestBody DeclarationFormVO declarationVO) {
        DeclarationFormHeadEntity headEntity = new DeclarationFormHeadEntity();
        BeanUtils.copyProperties(declarationVO, headEntity);
        List<DeclarationFormItemEntity> itemList = declarationVO.getItemList();
        //获取item中即将过期的有效期作为宣告表的有效期
        Date expireDate = itemList.stream().map(DeclarationFormItemEntity::getThirdExpiredate).min((a, b) -> a.after(b) ? 1 : -1).get();
        headEntity.setExpireDate(expireDate);
        headEntity.setCreator(this.getUser().getUsername());
        headEntity.setCreateDate(new Date());
        declarationFormHeadService.insert(headEntity);

        //保存item
        itemList.forEach(item -> {
            item.setHeadId(headEntity.getPkId());
            //通过报告库id获取附件，保存
            item.setThirdAttachment(reportService.selectById(item.getReportId()).getAttach());
            item.setCreator(this.getUser().getUsername());
            item.setCreateDate(new Date());
            declarationFormItemService.insert(item);
        });
        return R.ok();
    }

    /**
     * 宣告表审核
     *
     * @param nodeStatus 节点状态
     * @param headId     表id
     * @return
     */
    @RequiresPermissions("declarationForm:audit")
    @PostMapping("/audit")
    public R audit(Integer nodeStatus, String headId) {
        DeclarationFormHeadEntity headEntity = declarationFormHeadService.selectById(headId);
        //校核人
        headEntity.setReviewer(this.getUser().getName());
        //审核时间
        headEntity.setReviewDate(new Date());
        //节点状态
        headEntity.setNodeStatus(nodeStatus);
        //审核不通过，则生效状态改为无效
        if (!nodeStatus.equals(DeclarationFormHeadEntity.TG)) {
            headEntity.setValidStatus(DeclarationFormHeadEntity.WX);
        } else {
            headEntity.setValidStatus(DeclarationFormHeadEntity.SX);
        }
        declarationFormHeadService.updateById(headEntity);
        return R.ok();
    }
}